﻿#include "sos.h"

#include<avr/io.h>
#include<avr/Interrupt.h>

SIGNAL(SIG_INTERRUPT1)   /// K4中断
{
	DDRB = 0xff;
	PORTB = 0xff;
	PORTB = 0x0f;
	SOS_Delay();
	PORTB = 0xff;
}


void Task0()
{
	DDRD = 0xf0;
	PORTD = 0x0f;

	SREG = 0x80;	/// 开全局中断

	GICR = 0x80;   /// 开外部中断int_1,对应按键K4
	SOS_TaskSuspend(0);
}

void Task1()
{
	DDRB = 0xff;
	PORTB = 0xff;
	while(1)
	{
		PORTB = 0xfc;  /// led0、led1亮
		//SOS_Delay();
		//SOS_TimeDly(39);
	}
}

void Task2()
{
	DDRB = 0xff;
	PORTB = 0xff;
	while(1)
	{
		PORTB = 0xf3;  /// led2、led3亮
		//SOS_Delay();
		//SOS_TimeDly(79);
	}
}

void Task3()
{
	DDRB = 0xff;
	PORTB = 0xff;
	while(1)
	{
		PORTB = 0xcf;  /// led4~led7亮
		//SOS_Delay();
		//SOS_TimeDly(160);
	}
}

unsigned char encoder(unsigned char key)
{
	unsigned char num = 0xff;
	switch(key)
	{
  		case 0x00:	num=0xc0;break;
  		case 0x01:	num=0xf9;break;
		case 0x02:	num=0xa4;break;
  		case 0x03:	num=0xb0;break;
  		case 0x04:	num=0x99;break;
  		case 0x05:	num=0x92;break;
  		case 0x06:	num=0x82;break;
  		case 0x07:	num=0xf8;break;
  		case 0x08:	num=0x80;break;
		case 0x09:	num=0x90;break;
  	}
  	return(num);
}

/// 写74hc595函数
void sendbyte(unsigned char byte)
{	
   	unsigned char i,tem; 
   	byte = encoder(byte);	   /// 译码
	for(i=0;i<8;i++)		  
   	{
   		PORTA &= ~(1<<1);	/// clk 清零
		tem = (byte & 0x80);
		if(tem == 0)
		{
			PORTA &= ~(1<<3);   /// dat 清零
		}
		else
		{
			PORTA |= (1<<3);	/// dat 置1
		}
		byte = byte<<1;		 /// 数据左移1位
		PORTA|=(1<<1);	  /// clk=1
	}
	PORTA&=~(1<<2);   /// rclk=0
	PORTA|=(1<<2);	 /// rclk=1	
}

void Task4()
{
	unsigned char number;
	unsigned int i,j;
	DDRA=0xff;	  /// 初始化端口A
	PORTA=0xef;
	while(1)
	{
		PORTA|=(1<<7);			   /// 74ls138使能
	 	for(number = 0; number <= 9; number++)		 /// 循环发送0-9的数字
		{
			sendbyte(number);
			for(i = 0; i < 1600; i++)
			{
				for(j = 0; j < 20; j++);		   
			}
		}
	}
}

int main(void)
{
	//Task4();
	//DDRD = 0xf0;
	
	SOS_TaskCreate(Task0,0);
	SOS_TaskCreate(Task1,1);
	SOS_TaskCreate(Task2,2);
	SOS_TaskCreate(Task3,3);
	SOS_TaskCreate(Task4,4);
	
	SOS_Start();
	
}

